<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon effect="dark" :closable="false"></el-alert>

      <!-- 商品分类的级联选择框 -->
      <div class="cascader-box">
        <span>选择商品分类：</span>
        <el-cascader v-model="cascaderValue" :options="catelist" :props="cascaderProps" @change="onCascaderChange"></el-cascader>
      </div>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="onTabClick" type="border-card">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="onTagClose(i, scope.row)">
                  {{tag}}
                </el-tag>
                <el-input class="tag-input" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="onTagClose(i, scope.row)">
                  {{tag}}
                </el-tag>
                <el-input class="tag-input" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="onAddDialogClose">
      <!-- 添加参数的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="onEditDialogClose">
      <!-- 添加参数的表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editNewParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有的商品分类
      catelist: [],
      // 级联选择框的属性绑定对象
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      cascaderValue: [],
      // 当前激活的页签
      activeName: 'many',
      onlyTableData: [],
      manyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isBtnDisabled() {
      return this.cascaderValue.length !== 3
    },
    // 三级商品分类的Id
    cateId() {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    },
    // 对话框的标题文本
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  watch: {
    cascaderValue(newVal) {
      if (newVal.length !== 3) {
        this.onlyTableData = []
        this.manyTableData = []
      }
    }
  },
  methods: {
    // 获取所有商品分类的列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')

      this.catelist = res.data
    },
    // 监听级联选择框选中项变化的事件
    onCascaderChange(val) {
      if (val.length !== 3) {
        this.cascaderValue = []
        this.$message.warning('只允许为三级分类设置参数！')
        return
      }
      this.getParamsList()
    },
    // 页签组件的点击事件处理函数
    onTabClick() {
      this.getParamsList()
    },
    // 获取参数列表数据
    async getParamsList() {
      if (!this.cateId) return
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })

      if (res.meta.status !== 200) return this.$message.error('获取参数列表数据失败！')

      // 处理 attr_vals 的值，用空格将字符串分割为数组
      res.data.forEach(item => {
        if (item.attr_vals.trim().length === 0) {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(',')
        }
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 展示添加参数的对话框
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 监听添加对话框的关闭事件
    onAddDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新的参数
    async addNewParams() {
      const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      })

      if (res.meta.status !== 201) return this.$message.error('添加参数失败！')

      this.$message.success('添加参数成功！')
      this.getParamsList()
      this.addDialogVisible = false
    },
    // 展示修改的对话框
    async showEditDialog(attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`)

      if (res.meta.status !== 200) return this.$message.error('查询参数信息失败！')

      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭事件
    onEditDialogClose() {
      this.$refs.editFormRef.resetFields()
      this.editForm = {}
    },
    // 修改参数
    async editNewParams() {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.editForm.attr_sel
      })

      if (res.meta.status !== 200) return this.$message.error('修改参数失败！')

      this.$message.success('修改参数成功！')
      this.getParamsList()
      this.editDialogVisible = false
    },
    // 删除参数项
    async removeParams(attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return

      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)

      if (res.meta.status !== 200) return this.$message.error('删除失败！')

      this.$message.success('删除成功！')
      this.getParamsList()
    },
    // tag 标签被关闭的事件
    onTagClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr(row)
    },
    // 保存参数项到数据库
    async saveAttr(row) {
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })

      if (res.meta.status !== 200) return this.$message.error('更新参数失败！')

      this.$message.success('更新参数成功！')
    },
    // 监听文本框失去焦点的事件
    handleInputConfirm(row) {
      // 如果 input 里面没有任何值，则终止后续代码执行
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 转存 input 的值到一个常量中
      const inputValue = row.inputValue.trim()
      // 清空 input 的值
      row.inputValue = ''
      // 隐藏 input
      row.inputVisible = false
      // 把新增的参数值保存到 attr_vals 数组中
      row.attr_vals.push(inputValue)
      this.saveAttr(row)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.cascader-box {
  margin: 20px 0;
}

.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.tag-input {
  width: 150px;
}
</style>